package com.fmdj.dr.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.fmdj.common.exception.GlobalException;
import com.fmdj.common.util.MicroAppUtil;
import com.fmdj.common.util.PageUtils;
import com.fmdj.dr.db.dao.DriverDao;
import com.fmdj.dr.db.dao.DriverSettingsDao;
import com.fmdj.dr.db.dao.WalletDao;
import com.fmdj.dr.db.pojo.DriverSettingsEntity;
import com.fmdj.dr.db.pojo.WalletEntity;
import com.fmdj.dr.service.DriverService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class DriverServiceImpl implements DriverService {
    @Resource
    private DriverDao driverDao;

    @Resource
    private DriverSettingsDao driverSettingsDao;

    @Resource
    private WalletDao walletDao;

    @Resource
    MicroAppUtil microAppUtil;


    /**
     * 司机注册的逻辑
     */
    @Override
    @Transactional
    @LcnTransaction
    public String registerDriver(Map param) {
        //通过临时登录的凭证获取openId
        String code = MapUtil.getStr(param, "code");
        String openId = microAppUtil.getOpenId(code);

        //存储参数
        HashMap paramMap = new HashMap() {{
            put("openId", openId);
        }};

        //校验要注册的司机是否已经存在
        long driverExists = driverDao.existsDriver(paramMap);
        if (driverExists != 0) {
            throw new GlobalException("已经进行注册过了");
        }

        /**
         * 可以注册
         * */
        param.put("openId", openId);
        //保存司机记录
        driverDao.registerDriver(param);
        //查询司机的主键值
        String driverId = driverDao.getDriverId(openId);
        //查询司机的主键值


        /**
         * 保存司机设置的信息
         * */
        DriverSettingsEntity settings = new DriverSettingsEntity();
        settings.setDriverId(Long.parseLong(driverId));
        //保存settings记录
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("autoAccept", false);
        jsonObject.set("orientation", "");
        jsonObject.set("orderDistance", 0);
        jsonObject.set("rangeDistance", 5);
        jsonObject.set("listenService", true);
        settings.setSettings(jsonObject.toString());
        driverSettingsDao.insertDriversSettings(settings);

        //初始化司机的钱包记录
        //金额用bigdecimal
        WalletEntity wallet = new WalletEntity();
        wallet.setDriverId(Long.parseLong(driverId));
        wallet.setBalance(BigDecimal.valueOf(0));
        //让用户支付的时候再设置
        wallet.setPassword(null);
        walletDao.insert(wallet);
        return driverId;
    }

    @Override
    @Transactional
    @LcnTransaction
    public int updateDriverAuth(Map params) {
        return driverDao.updateDriverAuth(params);
    }

    @Override
    public HashMap login(String code) {
        //获取到openid
        String openId = microAppUtil.getOpenId(code);
        //调用数据库查询
        HashMap loginResult = driverDao.login(openId);
        /**
         * 判断是否满足条件，采集过人脸信息
         * archive:是否在腾讯云归档存放司机面部信息（是否做过人脸采集）
         */
        if (loginResult != null) {
            if (loginResult.containsKey("archive")) {
                int temp = MapUtil.getInt(loginResult, "archive");
                //如果archive==1的话就表示司机录入过人脸信息
                boolean archive = temp == 1;
                //保存为true或者false
                loginResult.replace("archive", archive);
            }
        }
        return loginResult;
    }

    /**
     * 查询司机个人信息
     */
    @Override
    public HashMap selectDriverInfo(long driverId) {
        HashMap hashMap = driverDao.selectDriverInfo(driverId);
        JSONObject summary = JSONUtil.parseObj(MapUtil.getStr(hashMap, "summary"));
        hashMap.replace("summary", summary);
        return hashMap;
    }

    @Override
    public HashMap selectDriverInfoById(long driverId) {
        return driverDao.selectDriverInfoById(driverId);
    }

    @Override
    public PageUtils selectDriverByPage(Map map) {
        ArrayList<HashMap> lists = null;
        long count = driverDao.selectDriverByCount(map);
        if (count == 0) {
            lists = new ArrayList<>();
        } else {
            lists = driverDao.selectDriverByPage(map);
        }

        //取出来分页参生成PageUtils实例
        int start = (Integer)map.get("start");
        int length = (Integer)map.get("length");
        PageUtils pageUtils = new PageUtils(lists,count,start,length);
        return pageUtils;

    }

    @Override
    public HashMap selectDriverAuthInfo(long driverId) {
        return driverDao.selectDriverAuthInfo(driverId);
    }

    @Override
    @Transactional
    @LcnTransaction
    public int updateDriverRealAuth(Map param) {
        return driverDao.updateDriverRealAuth(param);
    }


}
